<template>
  <div class="post-detail">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="帖子详情"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    >
      <template #right>
        <van-icon name="share-o" @click="sharePost" />
      </template>
    </van-nav-bar>

    <div class="detail-container" v-if="postDetail">
      <!-- 帖子内容 -->
      <div class="post-content">
        <!-- 用户信息 -->
        <div class="user-info">
          <img :src="postDetail.avatar || defaultAvatar" class="avatar" />
          <div class="user-details">
            <div class="nickname">{{ postDetail.nickname || '匿名用户' }}</div>
            <div class="post-time">{{ formatTime(postDetail.createTime) }}</div>
          </div>
          <div class="post-status">
            <span v-if="postDetail.isResolved" class="status-tag resolved">已解决</span>
            <span v-else class="status-tag pending">求助中</span>
          </div>
        </div>

        <!-- 帖子标题和内容 -->
        <div class="post-main">
          <h2 class="post-title">{{ postDetail.title }}</h2>
          <div class="post-text">{{ postDetail.content }}</div>
          
          <!-- 图片展示 -->
          <div v-if="postDetail.images && postDetail.images.length" class="post-images">
            <img
              v-for="(image, index) in postDetail.images"
              :key="index"
              :src="image"
              class="post-image"
              @click="previewImage(postDetail.images, index)"
            />
          </div>

          <!-- 标签 -->
          <div v-if="postDetail.tags" class="post-tags">
            <span
              v-for="tag in postDetail.tags.split(',')"
              :key="tag"
              class="tag"
            >
              {{ tag }}
            </span>
          </div>

          <!-- 涉及金额 -->
          <div v-if="postDetail.involvedAmount" class="involved-amount">
            <van-icon name="gold-coin-o" />
            <span>涉及金额：¥{{ postDetail.involvedAmount }}</span>
          </div>
        </div>

        <!-- 帖子统计 -->
        <div class="post-stats">
          <div class="stat-item">
            <van-icon name="eye-o" />
            <span>{{ postDetail.viewCount }} 浏览</span>
          </div>
          <div class="stat-item">
            <van-icon name="chat-o" />
            <span>{{ postDetail.commentCount }} 评论</span>
          </div>
          <div class="stat-item">
            <van-icon name="clock-o" />
            <span>{{ formatTime(postDetail.createTime) }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="post-actions">
          <div
            class="action-btn"
            :class="{ active: postDetail.isLiked }"
            @click="toggleLike"
          >
            <van-icon :name="postDetail.isLiked ? 'good-job' : 'good-job-o'" />
            <span>{{ postDetail.isLiked ? '已点赞' : '点赞' }} ({{ postDetail.likeCount }})</span>
          </div>
          <div
            class="action-btn"
            :class="{ active: postDetail.isCollected }"
            @click="toggleCollect"
          >
            <van-icon :name="postDetail.isCollected ? 'star' : 'star-o'" />
            <span>{{ postDetail.isCollected ? '已收藏' : '收藏' }}</span>
          </div>
          <div class="action-btn" @click="showReportDialog = true">
            <van-icon name="warning-o" />
            <span>举报</span>
          </div>
        </div>

        <!-- 状态更新按钮（仅作者可见） -->
        <div v-if="isAuthor" class="author-actions">
          <van-button
            v-if="!postDetail.isResolved"
            type="success"
            size="small"
            @click="markAsResolved"
          >
            标记为已解决
          </van-button>
          <van-button
            v-else
            type="warning"
            size="small"
            @click="markAsPending"
          >
            标记为求助中
          </van-button>
        </div>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <div class="comments-header">
          <h3>全部评论 ({{ commentList.length }})</h3>
          <div class="sort-options">
            <span
              :class="{ active: commentSort === 'latest' }"
              @click="changeCommentSort('latest')"
            >
              最新
            </span>
            <span
              :class="{ active: commentSort === 'hot' }"
              @click="changeCommentSort('hot')"
            >
              最热
            </span>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <div
            v-for="comment in commentList"
            :key="comment.id"
            class="comment-item"
          >
            <div class="comment-header">
              <img :src="comment.avatar || defaultAvatar" class="comment-avatar" />
              <div class="comment-user">
                <div class="comment-nickname">{{ comment.nickname || '匿名用户' }}</div>
                <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
              </div>
              <div class="comment-actions">
                <div
                  class="comment-like"
                  :class="{ active: comment.isLiked }"
                  @click="toggleCommentLike(comment)"
                >
                  <van-icon :name="comment.isLiked ? 'good-job' : 'good-job-o'" />
                  <span v-if="comment.likeCount > 0">{{ comment.likeCount }}</span>
                </div>
              </div>
            </div>
            
            <div class="comment-content">{{ comment.content }}</div>
            
            <!-- 评论图片 -->
            <div v-if="comment.images && comment.images.length" class="comment-images">
              <img
                v-for="(image, index) in comment.images"
                :key="index"
                :src="image"
                class="comment-image"
                @click="previewImage(comment.images, index)"
              />
            </div>

            <!-- 回复按钮 -->
            <div class="comment-reply">
              <span @click="replyToComment(comment)">回复</span>
            </div>

            <!-- 子评论 -->
            <div v-if="comment.replies && comment.replies.length" class="replies">
              <div
                v-for="reply in comment.replies"
                :key="reply.id"
                class="reply-item"
              >
                <div class="reply-header">
                  <img :src="reply.avatar || defaultAvatar" class="reply-avatar" />
                  <div class="reply-user">
                    <span class="reply-nickname">{{ reply.nickname || '匿名用户' }}</span>
                    <span v-if="reply.replyToNickname" class="reply-to">
                      回复 @{{ reply.replyToNickname }}
                    </span>
                  </div>
                  <div class="reply-time">{{ formatTime(reply.createTime) }}</div>
                </div>
                <div class="reply-content">{{ reply.content }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多评论 -->
        <div v-if="hasMoreComments" class="load-more" @click="loadMoreComments">
          <van-loading v-if="loadingComments" size="16px" />
          <span v-else>加载更多评论</span>
        </div>
      </div>
    </div>

    <!-- 底部评论输入框 -->
    <div class="comment-input-bar">
      <div class="input-container">
        <van-field
          v-model="commentText"
          placeholder="写下你的评论..."
          type="textarea"
          rows="1"
          autosize
          maxlength="500"
          show-word-limit
        />
        <div class="input-actions">
          <van-icon name="photograph" @click="selectCommentImage" />
          <van-button
            type="primary"
            size="small"
            :disabled="!commentText.trim()"
            @click="submitComment"
          >
            发送
          </van-button>
        </div>
      </div>
    </div>

    <!-- 举报对话框 -->
    <van-dialog
      v-model:show="showReportDialog"
      title="举报帖子"
      show-cancel-button
      @confirm="submitReport"
    >
      <van-radio-group v-model="reportReason">
        <van-cell-group>
          <van-cell title="垃圾信息" clickable @click="reportReason = '垃圾信息'">
            <template #right-icon>
              <van-radio name="垃圾信息" />
            </template>
          </van-cell>
          <van-cell title="违法违规" clickable @click="reportReason = '违法违规'">
            <template #right-icon>
              <van-radio name="违法违规" />
            </template>
          </van-cell>
          <van-cell title="虚假信息" clickable @click="reportReason = '虚假信息'">
            <template #right-icon>
              <van-radio name="虚假信息" />
            </template>
          </van-cell>
          <van-cell title="其他" clickable @click="reportReason = '其他'">
            <template #right-icon>
              <van-radio name="其他" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-dialog>

    <!-- 图片选择器 -->
    <input
      ref="imageInput"
      type="file"
      accept="image/*"
      multiple
      style="display: none"
      @change="handleImageSelect"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showImagePreview, showConfirmDialog } from 'vant'
import { useUserStore } from '@/stores/user'
import {
  getPostDetail,
  getComments,
  addComment,
  likePost,
  collectPost,
  likeComment,
  reportPost,
  updatePostStatus
} from '@/api/community'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const postDetail = ref(null)
const commentList = ref([])
const commentText = ref('')
const commentSort = ref('latest')
const loadingComments = ref(false)
const hasMoreComments = ref(true)
const showReportDialog = ref(false)
const reportReason = ref('')
const defaultAvatar = 'https://img.yzcdn.cn/vant/cat.jpeg'
const imageInput = ref(null)
const selectedImages = ref([])

// 分页参数
const commentParams = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 计算属性
const isAuthor = computed(() => {
  return userStore.userInfo && postDetail.value && 
         userStore.userInfo.id === postDetail.value.userId
})

// 方法
const loadPostDetail = async () => {
  try {
    const response = await getPostDetail(route.params.id)
    if (response.code === 200) {
      postDetail.value = {
        ...response.data,
        avatar: response.data.avatar || defaultAvatar,
        nickname: response.data.isAnonymous ? '匿名用户' : (response.data.nickname || '用户'),
        images: response.data.images ? 
          (typeof response.data.images === 'string' ? response.data.images.split(',') : response.data.images) : [],
        tags: response.data.tags || '',
        isLiked: response.data.isLiked || false,
        isCollected: response.data.isCollected || false
      }
    } else {
      showToast(response.message || '加载失败')
      router.go(-1)
    }
  } catch (error) {
    console.error('加载帖子详情失败:', error)
    showToast('网络错误，请重试')
    router.go(-1)
  }
}

const loadComments = async (reset = false) => {
  if (reset) {
    commentParams.current = 1
    commentList.value = []
    hasMoreComments.value = true
  }

  loadingComments.value = true

  try {
    const params = {
      current: commentParams.current,
      size: commentParams.size,
      sortBy: commentSort.value
    }

    const response = await getComments(route.params.id, params)
    
    if (response.code === 200) {
      const data = response.data
      const newComments = data.records || data || []
      
      // 处理评论数据
      const processedComments = newComments.map(comment => ({
        ...comment,
        avatar: comment.avatar || defaultAvatar,
        nickname: comment.isAnonymous ? '匿名用户' : (comment.nickname || '用户'),
        images: comment.images ? 
          (typeof comment.images === 'string' ? comment.images.split(',') : comment.images) : [],
        isLiked: comment.isLiked || false,
        likeCount: comment.likeCount || 0,
        replies: comment.replies || []
      }))

      if (reset) {
        commentList.value = processedComments
      } else {
        commentList.value.push(...processedComments)
      }

      commentParams.current++
      
      if (processedComments.length < commentParams.size) {
        hasMoreComments.value = false
      }
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    showToast('加载评论失败')
  } finally {
    loadingComments.value = false
  }
}

const loadMoreComments = () => {
  if (!loadingComments.value && hasMoreComments.value) {
    loadComments()
  }
}

const changeCommentSort = (sort) => {
  commentSort.value = sort
  loadComments(true)
}

const toggleLike = async () => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }

  try {
    await likePost(postDetail.value.id)
    postDetail.value.isLiked = !postDetail.value.isLiked
    postDetail.value.likeCount += postDetail.value.isLiked ? 1 : -1
    showToast(postDetail.value.isLiked ? '点赞成功' : '取消点赞')
  } catch (error) {
    console.error('点赞操作失败:', error)
    showToast('操作失败')
  }
}

const toggleCollect = async () => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }

  try {
    await collectPost(postDetail.value.id)
    postDetail.value.isCollected = !postDetail.value.isCollected
    showToast(postDetail.value.isCollected ? '收藏成功' : '取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    showToast('操作失败')
  }
}

const toggleCommentLike = async (comment) => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }

  try {
    await likeComment(comment.id)
    comment.isLiked = !comment.isLiked
    comment.likeCount += comment.isLiked ? 1 : -1
  } catch (error) {
    console.error('评论点赞失败:', error)
    showToast('操作失败')
  }
}

const submitComment = async () => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }

  if (!commentText.value.trim()) {
    showToast('请输入评论内容')
    return
  }

  try {
    const commentData = {
      postId: parseInt(route.params.id),
      content: commentText.value.trim(),
      images: selectedImages.value.join(',')
    }

    const response = await addComment(commentData)
    
    if (response.code === 200) {
      showToast('评论成功')
      commentText.value = ''
      selectedImages.value = []
      
      // 重新加载评论
      loadComments(true)
      
      // 更新帖子评论数
      if (postDetail.value) {
        postDetail.value.commentCount++
      }
    } else {
      showToast(response.message || '评论失败')
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    showToast('评论失败，请重试')
  }
}

const replyToComment = (comment) => {
  // 这里可以实现回复功能，比如在输入框中添加@用户名
  commentText.value = `@${comment.nickname} `
  // 可以添加更多回复逻辑
}

const markAsResolved = async () => {
  try {
    const confirmed = await showConfirmDialog({
      title: '确认操作',
      message: '确定要标记为已解决吗？'
    })
    
    if (confirmed) {
      await updatePostStatus(postDetail.value.id, 1)
      postDetail.value.isResolved = true
      showToast('已标记为已解决')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新状态失败:', error)
      showToast('操作失败')
    }
  }
}

const markAsPending = async () => {
  try {
    const confirmed = await showConfirmDialog({
      title: '确认操作',
      message: '确定要标记为求助中吗？'
    })
    
    if (confirmed) {
      await updatePostStatus(postDetail.value.id, 0)
      postDetail.value.isResolved = false
      showToast('已标记为求助中')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新状态失败:', error)
      showToast('操作失败')
    }
  }
}

const submitReport = async () => {
  if (!reportReason.value) {
    showToast('请选择举报原因')
    return
  }

  try {
    await reportPost(postDetail.value.id, {
      reason: reportReason.value,
      description: ''
    })
    showToast('举报成功，我们会尽快处理')
    showReportDialog.value = false
    reportReason.value = ''
  } catch (error) {
    console.error('举报失败:', error)
    showToast('举报失败，请重试')
  }
}

const selectCommentImage = () => {
  imageInput.value.click()
}

const handleImageSelect = (event) => {
  const files = Array.from(event.target.files)
  if (files.length === 0) return

  // 这里可以添加图片上传逻辑
  // 暂时模拟图片URL
  files.forEach(file => {
    const url = URL.createObjectURL(file)
    selectedImages.value.push(url)
  })

  showToast(`已选择${files.length}张图片`)
}

const sharePost = () => {
  // 实现分享功能
  if (navigator.share) {
    navigator.share({
      title: postDetail.value.title,
      text: postDetail.value.content,
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href)
    showToast('链接已复制到剪贴板')
  }
}

const previewImage = (images, startPosition) => {
  showImagePreview({
    images,
    startPosition,
    closeable: true
  })
}

const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return timeStr.split(' ')[0]
}

onMounted(() => {
  loadPostDetail()
  loadComments(true)
})
</script>

<style scoped>
.post-detail {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 80px;
}

.detail-container {
  padding-top: 46px;
}

.post-content {
  background: white;
  padding: 16px;
  margin-bottom: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
}

.user-details {
  flex: 1;
}

.nickname {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 4px;
}

.post-time {
  font-size: 12px;
  color: #969799;
}

.status-tag {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
}

.status-tag.resolved {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.pending {
  background: #fff7e6;
  color: #ff976a;
}

.post-main {
  margin-bottom: 16px;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  line-height: 1.4;
  margin: 0 0 12px 0;
}

.post-text {
  font-size: 15px;
  color: #646566;
  line-height: 1.6;
  margin-bottom: 16px;
  white-space: pre-wrap;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

.post-image {
  width: 100%;
  height: 100px;
  border-radius: 8px;
  object-fit: cover;
  cursor: pointer;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

.tag {
  font-size: 12px;
  padding: 4px 8px;
  background: #f0f9ff;
  color: #1989fa;
  border-radius: 4px;
}

.involved-amount {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #ff6b35;
  font-weight: 500;
  margin-bottom: 16px;
}

.post-stats {
  display: flex;
  gap: 20px;
  padding: 12px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #969799;
}

.post-actions {
  display: flex;
  gap: 16px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: #f8f9fa;
  border-radius: 20px;
  font-size: 14px;
  color: #646566;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.active {
  background: #e8f4ff;
  color: #1989fa;
}

.action-btn:hover {
  background: #e9ecef;
}

.author-actions {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.comments-section {
  background: white;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.comments-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.sort-options {
  display: flex;
  gap: 16px;
}

.sort-options span {
  font-size: 14px;
  color: #969799;
  cursor: pointer;
  transition: color 0.2s;
}

.sort-options span.active {
  color: #1989fa;
  font-weight: 500;
}

.comments-list {
  padding: 0 16px;
}

.comment-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
}

.comment-user {
  flex: 1;
}

.comment-nickname {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
}

.comment-time {
  font-size: 12px;
  color: #969799;
}

.comment-actions {
  display: flex;
  align-items: center;
}

.comment-like {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #969799;
  cursor: pointer;
  transition: color 0.2s;
}

.comment-like.active {
  color: #1989fa;
}

.comment-content {
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
  margin-bottom: 8px;
  white-space: pre-wrap;
}

.comment-images {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.comment-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  object-fit: cover;
  cursor: pointer;
}

.comment-reply {
  font-size: 12px;
  color: #1989fa;
  cursor: pointer;
}

.replies {
  margin-top: 12px;
  padding-left: 40px;
  border-left: 2px solid #f0f0f0;
}

.reply-item {
  padding: 8px 0;
  border-bottom: 1px solid #f8f9fa;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.reply-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.reply-nickname {
  font-size: 12px;
  font-weight: 500;
  color: #323233;
}

.reply-to {
  font-size: 12px;
  color: #1989fa;
}

.reply-time {
  font-size: 12px;
  color: #969799;
  margin-left: auto;
}

.reply-content {
  font-size: 13px;
  color: #646566;
  line-height: 1.4;
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  font-size: 14px;
  color: #1989fa;
  cursor: pointer;
}

.comment-input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #eee;
  padding: 12px 16px;
  z-index: 100;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 12px;
}

.input-container .van-field {
  flex: 1;
  background: #f8f9fa;
  border-radius: 20px;
}

.input-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-actions .van-icon {
  font-size: 20px;
  color: #969799;
  cursor: pointer;
}

.input-actions .van-button {
  border-radius: 16px;
}
</style>
